package com.liukaixin.product.ru.business.team.teamlist;

import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;

import com.liukaixin.product.ru.data.CallBackListener;
import com.liukaixin.product.ru.data.model.Team;
import com.liukaixin.product.ru.data.repositories.TeamsRepository;

import java.util.List;

import static com.google.gson.internal.$Gson$Preconditions.checkNotNull;

/**
 * 团队列表逻辑控制层.
 * <p>
 * Created by Jacob on 2016/9/5.
 */
public class TeamsPresenter implements TeamsContract.Presenter {

    // 数据仓库
    private final TeamsRepository teamsRepository;

    // 视图层
    private final TeamsContract.View teamsView;

    private Handler handler = new Handler();

    public TeamsPresenter(@NonNull TeamsRepository teamsRepository,
                          @NonNull TeamsContract.View teamsView) {
        this.teamsRepository = checkNotNull(teamsRepository);
        this.teamsView = checkNotNull(teamsView);

        this.teamsView.setPresenter(this);
    }

    public void refresh() {
        teamsView.initPage();
        //获取第一页
        getDataByLoginStatus(1);
    }

    /**
     * 获得发布状态的团队.
     *
     * @param page 页码
     * @param rows 条数
     */
    public void getReleasedTeams(Integer page, Integer rows) {
        teamsRepository.getReleaseTeams(page, rows, new CallBackListener<List<Team>>() {
            @Override
            public void onCompleted() {
                //do nothing
            }

            @Override
            public void onError(String msg) {
                teamsView.showError(msg);
            }

            @Override
            public void onNext(List<Team> teams) {
                showDataOnView(teams, page);
            }
        });
    }

    @Override
    public void loadMore(Integer page) {
        getDataByLoginStatus(page);
    }

    private void showDataOnView(List<Team> teams, Integer page) {
        handler.postDelayed(() -> {
            // 没有数据
            if (page == 1 && teams.isEmpty()) {
                teamsView.showNoData();
                return;
            }
            if (page == 1) {
                teamsView.clearAdapter();
            }
            // 最后一页数据且<10 或 非第一页且数据为0
            if (teams.size() % 10 > 0 || (page != 1 && teams.isEmpty())) {
                teamsView.setNoMoreData();
            }
            teamsView.showData(teams);
        }, 1000);
    }

    private void getDataByLoginStatus(Integer page) {
        getReleasedTeams(page, 10);
    }
}
